package com.wiki.KBS.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wiki.KBS.domian.Ebook;
import com.wiki.KBS.domian.EbookExample;
import com.wiki.KBS.mapper.EbookMapper;
import com.wiki.KBS.request.EbookReq;
import com.wiki.KBS.request.EbookSaveReq;
import com.wiki.KBS.response.EbookQueryResp;
import com.wiki.KBS.response.PageResp;
import com.wiki.KBS.utils.CopyUtil;
import com.wiki.KBS.utils.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
@Slf4j
@Service
public class EbookService {

    @Autowired
    private EbookMapper ebookMapper;
    @Autowired
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> ebookList(EbookReq req){
        EbookExample ebookExample = new EbookExample();
        //  创建查询条件
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        // 增加一个判断，当有name值时才按name查询；
        if(!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%"+req.getName()+"%");
        }
        // 增加一个判断，当有 categoryId2 值时才按 categoryId2 查询；
        if(!ObjectUtils.isEmpty(req.getCategoryId2())){
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }
        // 把查询结果存入Ebook类型的列表里面
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);
        List<EbookQueryResp> ebookQueryResps = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        // 查询页面信息
        PageInfo<Ebook> PageInfo = new PageInfo<>(ebookList);
        log.info("总行数：{}",PageInfo.getTotal());
        log.info("总页数：{}",PageInfo.getPages());

        PageResp<EbookQueryResp> PageResp = new PageResp<>();
        PageResp.setTotal(PageInfo.getTotal());
        PageResp.setList(ebookQueryResps);
        return  PageResp;
    }

    /**
     * 保存
     */
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            // 更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
